/* eslint-disable  */
import ImageToBlob from './imgHandle';
import { uploadToken } from '../api/Cache';

export default class {
    constructor(driver = 'qiniu') {
        this.driver = driver;
    }

    /**
     * 设置图片压缩选项
     * @param imgOptions
     */
    imgOptions(imgOptions) {
        this.imgOptions = imgOptions;
        return this;
    }

    /**
     * 设置ajax请求选项
     * @param ajaxOptions
     */
    ajaxOptions(ajaxOptions) {
        this.ajaxOptions = ajaxOptions;
        return this;
    }

    /**
     * 把单个文件转成文件数组
     * @param files
     */
    fileToFiles(files) {
        if (typeof files.length === 'undefined') files = [files];
        return files;
    }

    /**
     * 获取上传进度获取
     * @param callback
     */
    onUploadProgress(callback) {
        if (!this.ajaxOptions) this.ajaxOptions = {};
        this.ajaxOptions.onUploadProgress = callback;
        return this;
    }

    /**
     * 获取上传参数
     * @param driver
     * @return {Promise<*>}
     */
    uploadParameter(driver = null, dir = null) {
        if (driver) this.driver = driver;
        return uploadToken(this.driver, dir);
    }

    /**
     *
     * @param parameter
     * @return {*}
     */
    handleUploadParameter(parameter) {
        if (!this.ajaxOptions) this.ajaxOptions = {};
        if (!(this.ajaxOptions.headers instanceof Object)) this.ajaxOptions.headers = {};
        if (parameter.headers instanceof Object) Object.assign(this.ajaxOptions.headers, parameter.headers);

        return parameter;
    }

    /**
     * 开始批量上传
     * @param files
     * @return {Promise<Array>}
     */
    async uploadStart(files) {
        if (files) files = this.fileToFiles(files);

        const filesUrl = [];
        for (let i = 0; i < files.length; i++) {
            filesUrl.push(await this.uploadFile(files[i]));
        }
        return filesUrl;
    }

    /**
     * 上传单个文件
     * @param file
     * @return {Promise<*>}
     */
    async uploadFile(file, dir = null, driver = null) {
        const uploadParameter = this.handleUploadParameter(await this.uploadParameter(driver, dir));
        const uploadForm = uploadParameter.form;
        if (this.imgOptions) {
            file = await ImageToBlob(file, this.imgOptions);
        }
        uploadForm[uploadParameter.file_field] = file;
        const formData = new FormData();
        Object.entries(uploadForm).forEach(([key, value]) => {
            if (key === uploadParameter.file_field) {
                formData.append(key, value, value.name);
            } else {
                formData.append(key, value);
            }
        });
        this.ajaxOptions = {
            ...this.ajaxOptions,
            // withCredentials: true,
        }
        const method = uploadParameter.method.toLowerCase();
        await axios[method](uploadParameter.upload_url, formData, this.ajaxOptions);
        return uploadParameter.access_url;
    }
}
